package com.zmn.oms.zmn.aop;

import com.zmn.oms.common.dto.OmsBaseOperator;
import com.zmn.oms.common.dto.OmsOperator;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.datasync.ElasticSearchDataSyncService;
import com.zmn.oms.services.interfaces.order.OrderChangeService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.util.Arrays;
import java.util.List;


/**
 * 订单修改后，ES 同步处理
 */
@Aspect
@Configuration
@ConditionalOnProperty(name = "elastic.sync.type", havingValue = "aop", matchIfMissing = true)
@Order(-2)
public class ZsChangeSyncToEsAspect {

    private static Logger logger = LoggerFactory.getLogger(ZsChangeSyncToEsAspect.class);

    @Autowired
    private OrderChangeService orderChangeService;
    @Autowired
    private ElasticSearchDataSyncService elasticSearchDataSyncService;
    /**
     * 设定切入点
     */
    @Pointcut("@annotation(com.zmn.oms.common.annotation.ZsNormalOrderWorkLog) || @annotation(com.zmn.oms.common.annotation.OrderWorkChangeSync) || @annotation(com.zmn.oms.common.annotation.ZsMemberOrderWorkLog)")
    private void orderPointCut() {
    }

    @After("orderPointCut()")
    public void orderDoAfter(JoinPoint joinPoint) {

        Long orderId = null;
        if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
            if (joinPoint.getArgs()[0] instanceof OmsOperator) {
                OmsOperator omsOperator = (OmsOperator) joinPoint.getArgs()[0];
                orderId = omsOperator.getOrderId();
            } else if (joinPoint.getArgs()[0] instanceof OrderWork) {
                OrderWork orderWork = (OrderWork) joinPoint.getArgs()[0];
                orderId = orderWork.getOrderId();
            } else if (joinPoint.getArgs()[0] instanceof OmsBaseOperator) {
                OmsBaseOperator omsBaseOperator = (OmsBaseOperator) joinPoint.getArgs()[0];
                orderId = omsBaseOperator.getOrderId();
            }
        }

        if (orderId != null) {
            logger.info("aop#elastic同步--->orderId:{}", orderId);
            elasticSearchDataSyncService.syncWorkIndex(orderId);
            elasticSearchDataSyncService.syncPartIndex(orderId);
            elasticSearchDataSyncService.syncPerfOrderWorkIndex(orderId);
            orderChangeService.changeSyncToMos(orderId);
        }
    }

}
